from fastapi import FastAPI, HTTPException
from fastapi.middleware.cors import CORSMiddleware
from app.api.v1 import diagnosis
from app.utils.logger import setup_logger
import torch

app = FastAPI(
    title="植物诊断AI系统",
    description="基于深度学习的植物健康诊断API，支持水分状态和病虫害识别",
    version="1.0.0"
)

# 添加CORS中间件
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],  # 生产环境中应该指定具体域名
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

app.include_router(diagnosis.router, prefix="/api/v1")

logger = setup_logger(__name__)

@app.get("/")
def root():
    return {
        "message": "欢迎使用植物诊断AI系统",
        "version": "1.0.0",
        "docs": "/docs"
    }

@app.get("/health")
def health_check():
    """健康检查端点"""
    try:
        # 检查CUDA可用性
        cuda_available = torch.cuda.is_available()
        device_info = "CUDA" if cuda_available else "CPU"
        
        return {
            "status": "healthy",
            "device": device_info,
            "cuda_available": cuda_available
        }
    except Exception as e:
        logger.error(f"健康检查失败: {str(e)}")
        raise HTTPException(status_code=500, detail="服务异常")

@app.get("/info")
def get_info():
    """获取系统信息"""
    return {
        "system": "植物诊断AI系统",
        "models": ["水分诊断模型", "病虫害诊断模型"],
        "supported_formats": ["JPEG", "PNG", "JPG"],
        "max_file_size": "10MB"
    }